//
//  IndexController.m
//  Weibo
//
//  Created by wpapple on 16/5/30.
//  Copyright © 2016年 红红火火恍恍惚惚嘿嘿嘿. All rights reserved.
//

#import "IndexController.h"
#import "UIImage+XL.h"
#import "IWStatus.h"
#import "Account.h"
#import "indexTableViewCell.h"
#import "indexTableViewFotter.h"
#import "coverView.h"
#import "TextViewController.h"

static NSString * identifier = @"cell";

@interface IndexController ()

@property (strong , nonatomic) UIImageView * AIamgeView;
@property (strong , nonatomic) UITableView * ATableView;
@property (strong , nonatomic) NSMutableArray * statuses;

@end

@implementation IndexController

-(NSMutableArray *)statuses{
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}

-(UITableView *)ATableView{
    if (!_ATableView) {
        _ATableView = [[UITableView alloc]init];
    }
    return _ATableView;
}

-(UIImageView *)AIamgeView{
    if (!_AIamgeView) {
        _AIamgeView = [[UIImageView alloc]init];
    }
    return _AIamgeView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    BOOL isLogin = [Account isLogin];
    if (isLogin) {
        [self loadNewStatuses];
        self.refreshControl = [[UIRefreshControl alloc]init];
        [self.refreshControl addTarget:self action:@selector(loadNewStatuses) forControlEvents:UIControlEventValueChanged];
        
    }
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self.tabBarItem setImage:[UIImage imageNamed:@"tabbar_home"]];
        [self.tabBarItem setSelectedImage:[UIImage imageNamed:@"tabbar_home_selected"]];
        self.title = @"首页";
    }
    return self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return self.statuses.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    indexTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    IWStatus * status = self.statuses[indexPath.row];
    cell.status = status;
    return cell;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat constOffSetY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.height;
    
    if (self.tableView.tableFooterView != nil || self.statuses.count == 0) {
        return;
    }
    if (scrollView.contentOffset.y >= constOffSetY) {
        self.tableView.tableFooterView = [indexTableViewFotter FootViewLoadNib];
        [self loadMoreStatuses];
    }
}

- (IBAction)TouchTopButton:(UIButton *)sender {
    
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        
        CGRect rect = [window convertRect:sender.frame fromView:sender.superview];
        
        CGPoint point = [window convertPoint:sender.center fromView:sender.superview];
        
        UIImage * image = [UIImage resizableImage:@"popover_background"];
        
        self.AIamgeView.size = CGSizeMake(200, 200);
        
        self.AIamgeView.center = point;
        self.AIamgeView.y = CGRectGetMaxY(rect);
        
        [self.AIamgeView setImage:image];

        self.ATableView.size = CGSizeMake(self.AIamgeView.width, self.AIamgeView.height);
        
        self.ATableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
        
        [self.ATableView setBackgroundColor:[UIColor clearColor]];
        
        [self.AIamgeView addSubview:self.ATableView];
        
        coverView * view = [[coverView alloc]initWithFrame:window.bounds];
        
        [view setBackgroundColor:[UIColor clearColor]];
        
        [view addSubview:self.AIamgeView];
        
        
        
        [window addSubview:view];
        

    }else{
        [self.AIamgeView removeFromSuperview];
    }

    
}

-(void)loadNewStatuses{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [Account accountFromSandbox].access_token;
    
    parameters[@"count"] = @20;
    
    NSString * firstStatusIDstr = [[self.statuses firstObject] idstr];
    
    if (firstStatusIDstr != nil) {
        parameters[@"since_id"] = firstStatusIDstr;
    }
    
    NSString * urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSArray * newStatus = responseObject[@"statuses"];
        
        NSLog(@"newStatus = %@",newStatus);
        
        NSArray * models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        
        [self.statuses addObjectsFromArray:models];
        
        NSRange range = NSMakeRange(0, models.count);
        
        NSIndexSet * indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:models atIndexes:indexSet];
        
        [self.tableView reloadData];
        
        [self.refreshControl endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
        [self.refreshControl endRefreshing];
    }];
}

-(void)loadMoreStatuses{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [Account accountFromSandbox].access_token;
    parameters[@"count"] = @20;
    
    NSString * lastStatusIDstr = [[self.statuses lastObject] idstr];
    
    if (lastStatusIDstr != nil) {
        parameters[@"max_id"] = @([lastStatusIDstr longLongValue] - 1);
    }
    
    NSString * urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    [manager GET:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSArray * newStatus = responseObject[@"statuses"];
        
        NSLog(@"newStatus = %@",newStatus);
        
        NSArray * models = [IWStatus objectArrayWithKeyValuesArray:newStatus];
        
        [self.statuses addObjectsFromArray:models];
        
        [self.tableView reloadData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.tableView.tableFooterView = nil;
        });
     
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
        self.tableView.tableFooterView = nil;
    }];
}




/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
